﻿using System;
using System.Web.Mvc;
using System.Web.Script.Serialization;
using Framework.Model;
using MvcApplication1.Framework;
using MvcApplication1.Models;
using MvcApplication1.Services;

namespace MvcApplication1.Controllers
{
    public class StoryController : Controller
    {
        public ActionResult Create()
        {
            var story = new Story();
            return View("Edit", story);
        }

        public ActionResult Edit(int storyId)
        {
            var repository = new Repository(new ConnectionStringLoader(), new CacheWrapper());
            var story = repository.Get<Story>(storyId);
            return View(story);
        }

        public ActionResult Edit2(int storyId)
        {
            var repository = new Repository(new ConnectionStringLoader(), new CacheWrapper());
            var story = repository.Get<Story>(storyId);
            return View(story);
        }

        public ActionResult Delete(int storyId)
        {
            try
            {
                var repository = new Repository(new ConnectionStringLoader(), new CacheWrapper());
                repository.Delete<Story>(s => s.Id == storyId);
                return Json(new {Success = true}, JsonRequestBehavior.AllowGet);
            }
            catch (Exception e)
            {
                return Json(new {Success = false, Error = e.Message}, JsonRequestBehavior.AllowGet);
            }
        }

        public ActionResult Save(Story story)
        {
            try
            {
                var repository = new Repository(new ConnectionStringLoader(), new CacheWrapper());
                repository.Save(story);
            }
            catch (Exception e)
            {
                return Json(new {Success = false, Error = e.Message});
            }
            return Json(new {Success = true, Model = new JavaScriptSerializer().Serialize(story)});
        }
    }
}

